<template>
  <div class="cluster-layer_container">
    cluster-layer
  </div>
</template>
<script>
import { isEmptyObject } from "@/utils/common/index";
import staticData from "../static-data/index";
export default {
  data() {
    return {
      map: null,
      clusterData: {},
      markerImageNameList: [], // 添加成功的图片name集合， 用于移除地图上的图片
    }
  },
  mounted() {
  },
  beforeDestroy() {
    this.removeMarkerImages();
  },
  methods: {
    async init(options) {
      this.instance = options.instance;
      this.instance.emit("domMounted", "success");
      this.map = options.map;
      const data = await this.getClusterData();
      console.log(data, "dataaaaaa");
      if (!isEmptyObject(data)) {
        this.clusterData = data;
        this.addClusterSource(this.clusterData);
        this.drawClusterLayer();
      };
    },

    // 获取聚合图数据
    getClusterData() {
      return new Promise((resolve, reject) => {
        const url = "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson";
        fetch(url)
          .then(response => response.json())
          .then(data => {
            resolve(staticData);
          })
          .catch(error => {
            console.error("获取cluster的数据失败 ===>>>::", error);
          });
      })
    },

    // 绘制聚合图层
    drawClusterLayer() {
      this.map.setCenter([-126.20033965180625, 46.250565068859004]);
      this.map.setZoom(2.8); 
      this.addClusterLayer();
      this.addCountLayer();
      this.clusterLayerClickEvent.call(this);
    },

    // 添加聚合图层source
    addClusterSource(data) {
      this.map.addSource("clusterSourceId", {
        type: "geojson",
        data,
      })
    },

    // 添加聚合图层Layer
    addClusterLayer() {
      const layerOptions = {
        id: "clusterLayerId",
        type: "circle",
        source: "clusterSourceId",
        maxzoom: 12,
        filter: ["has", "count"],
        paint: {
          "circle-color": ["step", ["get", "count"], "#140", 10, "#f90", 100, "#c40", 1000, "#f00"],
          "circle-radius": 50,
          "circle-opacity": 0.8,
          "circle-stroke-width": 3,
          "circle-stroke-color": "#fff"
        }
      };
      this.map.addLayer(layerOptions);
    },
    addCountLayer() {
      const layerOptions = {
        id: "countLayerId",
        type: "symbol",
        source: "clusterSourceId",
        maxzoom: 12,
        filter: ["has", "count"],
        layout: {
          "text-field": ["get", "count"],
          "text-size": 12,
        },
        paint: {
          "text-color": "#fff"
        }
      };
      this.map.addLayer(layerOptions);
    },

    
    // 聚合图层点击事件
    clusterLayerClickEvent() {
      let self = this;
      this.map.on("click", "clusterLayerId", function(e) {
        let features = self.map.queryRenderedFeatures(e.point, {
          layers: [ "clusterLayerId", ],
        });
        self.map.easeTo({
          center: features[0].geometry.coordinates,
          zoom: 10,
          duration: 2000,
        });
        self.drawMarker();
      })
    },

    // 添加marker图层
    drawMarker() {
      // this.loadAndAddMarkerImage()
      //   .then((res) => {
      //     // 添加marker图片成功
      //     console.log(res, "res======loadImgPromises");
      //     this.getMarkerData().then((markerData) => {
      //       console.log(markerData, "markerData======markerData");
      //       this.addMarkerSource(markerData);
      //       this.addMarkerLayer(); 
      //     })
      //   })
      //   .catch((err) => {
      //     // 添加marker图片失败
      //     console.log(err, "err======loadImgPromises");
      //   });

      this.map.addSource('markerSourceId', {
        type: 'vector',
        url: 'mapbox://examples.dl46ljcs'
      });

      this.map.loadImage(require("@/assets/images/device_default.png"), ((err, image) => {
        if(err) {
          console.log(err);
        } else {
          this.map.addImage("deviceDefaultImgUrl", image);
          this.getMarkerData().then((markerData) => {
            console.log(markerData, "markerData======markerData");
            // this.addMarkerSource(markerData);
            this.addMarkerLayer(); 
          })
        }
      }));

      this.map.loadImage(require("@/assets/images/device_selected.png"), ((err, image) => {
        if(err) {
          console.log(err);
        } else {
          this.map.addImage("deviceSelectdImgUrl", image);
          this.getMarkerData().then((markerData) => {
            console.log(markerData, "markerData======markerData");
            // this.addMarkerSource2(markerData);
            this.addMarkerLayer2(); 
          })
        }
      }));
    },

    // 下载marker图片并加载到map上
    loadAndAddMarkerImage() {
      const imgList = [
        {
          name: "deviceDefaultImgUrl", 
          url: require("@/assets/images/device_default.png"),
        },
        {
          name: "deviceSelectdImgUrl", 
          url: require("@/assets/images/device_selected.png"),
          // url: "@/assets/images/device_selected.png",
        },
        {
          name: "importantUserDefaultImgUrl", 
          url: require("@/assets/images/importantUser_default.png"),
        },
        {
          name: "importantUserSelectedImgUrl", 
          url: require("@/assets/images/importantUser_selected.png"),
        },
        {
          name: "userDefaultImgUrl", 
          url: require("@/assets/images/user_default.png"),
        },
        {
          name: "userSelectedImgUrl", 
          url: require("@/assets/images/user_selected.png"),
        },
      ];
      const loadImgPromises = imgList.map((imgObj) => {
        return new Promise((resolve, reject) => {
          if(this.map.hasImage(imgObj.name)) {
            console.warn(`image添加失败${imgObj.name}已经存在`);
            resolve(item);
          } else {
            this.map.loadImage(imgObj.url, ((err, image) => {
              if(err) {
                reject(err);
              } else {
                this.map.addImage(imgObj.name, image);
                this.markerImageNameList.push(imgObj.name);
                resolve(image);
              }
            })) 
          }
        })
      }); 
      return Promise.all(loadImgPromises);
    },

    // 移除地图上加载的所有marker图片
    removeMarkerImages() {
      markerImageNameList.forEach((imgName) => {
        if(this.map.hasImage(imgName)) {
          this.map.removeImage(imgName);
        }
      })
    },

    // 获取marker数据
    getMarkerData() {
      return new Promise((resolve, reject) => {
        const url = "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson";
        fetch(url)
          .then(response => response.json())
          .then(data => {
            resolve(data);
          })
          .catch(error => {
            console.error("获取marker点的数据失败 ===>>>::", error);
          });
      })
    },

    // 添加marker数据源
    addMarkerSource(data) {
      // this.map.addSource("markerSourceId", {
      //   type: "geojson",
      //   data,
      // });
      this.map.addSource("markerSourceId", {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
              {
                  type: "Feature",
                  geometry: {
                      type: "Point",
                      coordinates: [-76.4144, 25.0759]
                  }
              }
          ]
        }
      });
    },
    addMarkerSource2(data) {
      // this.map.addSource("markerSourceId2", {
      //   type: "geojson",
      //   data,
      // });
      this.map.addSource("markerSourceId2", {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
              {
                  type: "Feature",
                  geometry: {
                      type: "Point",
                      coordinates: [-77.4144, 25.0759]
                  }
              }
          ]
        }
      });
    },

    // 添加marker图层
    addMarkerLayer() {
      this.map.addLayer({
        id: "markerLayerId",
        type: "symbol",
        source: "markerSourceId",
        'source-layer': 'food_stores-8sw1vy',
        // filter: ["!", ["has", "count"]],
        layout: {
          "icon-image": "deviceDefaultImgUrl",
          "icon-size": 0.25,
        }
      });
    },
    addMarkerLayer2() {
      this.map.addLayer({
        id: "markerLayerId2",
        type: "symbol",
        source: "markerSourceId",
        'source-layer': 'food_stores-8sw1vy',
        // filter: ["!", ["has", "count"]],
        layout: {
          "icon-image": "deviceSelectdImgUrl",
          "icon-size": 0.25,
          "icon-offset": [0, 10]
        }
      });
    },
  }
}
</script>
<style lang="scss" scoped>
.cluster-layer {
  &_container {
    position: absolute;
    top: 50px;
    right: 20px;
    width: 300px;
    min-height: 200px;
    background-color: #fff;
  }
}
</style>